package com.yzyz.web.listener;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yzyz.bean.news.NewsBean;
import com.yzyz.bean.region.RegionBean;
import com.yzyz.bean.route.RouteGroupBean;
import com.yzyz.bean.scenic.ScenicBean;
import com.yzyz.data.CacheFactory;
import com.yzyz.data.RegionStore;
import com.yzyz.data.RouteGroupStore;
import com.yzyz.service.NewsService;
import com.yzyz.service.RegionService;
import com.yzyz.service.RouteGroupService;
import com.yzyz.service.ScenicService;
import com.yzyz.utils.CommonHandle;
import com.yzyz.utils.Config;
import com.yzyz.utils.TitleScenics;

public class InitializeWholeSiteListener implements ServletContextListener {
	Log logger = LogFactory.getLog(InitializeWholeSiteListener.class);
	@Override
	public void contextDestroyed(ServletContextEvent Event) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		
		ServletContext servletContext = event.getServletContext();
		Config.init(servletContext);//初始化配置文件
		//获得spring 的上下文
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		//初始化景区
		RegionService regionService = (RegionService)context.getBean("regionService");
		RegionStore regionStore 	= CacheFactory.getRegionStore();
		List<RegionBean> allRegions = regionService.init();
		regionStore.init(allRegions);
		logger.info(CommonHandle.now() + " Loaded " + allRegions.size() + " regions into cache");
		ScenicService scenicService = (ScenicService)context.getBean("scenicService");
		List<ScenicBean> scenics = new ArrayList<ScenicBean>(11);
		for(String scenicName: TitleScenics.scenicName){//初始化header
			System.out.println("ScenicName: " + scenicName);
			scenics.add(scenicService.findScenicByName(scenicName));
		}
		servletContext.setAttribute("titleScenics", scenics);
		//初始化行程
		RouteGroupService routeGroupService = (RouteGroupService)context.getBean("routeGroupService");
		List<RouteGroupBean> allGroups = routeGroupService.init();
		RouteGroupStore routeGroupStore = CacheFactory.getRouteGroupStore();
		routeGroupStore.init(allGroups);
		logger.info(CommonHandle.now() + " Loaded " + allGroups.size() + "routeGroups into cahce");
		//初始化旅游新闻
		NewsService newsService = (NewsService) context.getBean("newsService");
		List<NewsBean> news = newsService.init(1000);
		System.out.println("---NEWS SZIE----:" + news.size());
		CacheFactory.getNewsStore().init(news);
	}

}
